﻿/*
 Developed by: Deepak Lakhotia
 Developed on 09/10/2015
*/

using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.Net.Mail;
using Microsoft.AnalysisServices;
using Microsoft.SqlServer.Dts.Runtime;
using System.Configuration;
using System.Web.Configuration;
using System.IO;
using System.Collections;
using BIMonitoring.RS;
using System.Web.Services.Protocols;

namespace BIMonitoring
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            radioButton1.Text = "Windows Integrated Security  ( " + System.Security.Principal.WindowsIdentity.GetCurrent().Name + " )";
            int retry_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Number of Retries"].ToString());
            try
            {
                StreamWriter sw1 = new StreamWriter(System.Configuration.ConfigurationSettings.AppSettings["Log File"].ToString(), true);
                sw1.WriteLine("Date: " + System.DateTime.Now);
                sw1.WriteLine("=============================");

                //Initial Loading..................
                System.Configuration.Configuration configuration1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                textBox2.Text = configuration1.AppSettings.Settings["Report Server URL"].Value;
                textBox3.Text = configuration1.AppSettings.Settings["Report Manager URL"].Value;
                textBox11.Text = configuration1.AppSettings.Settings["SQL Server"].Value;
                textBox12.Text = BinaryToString(re_order(configuration1.AppSettings.Settings["SQL Password"].Value));
                textBox13.Text = configuration1.AppSettings.Settings["SQL User"].Value;
                textBox4.Text = configuration1.AppSettings.Settings["Integration Services Server"].Value;
                textBox6.Text = configuration1.AppSettings.Settings["Analysis Services Server"].Value;
                comboBox1.SelectedIndex = comboBox1.FindStringExact(configuration1.AppSettings.Settings["SMTP Server"].Value);
                textBox7.Text = configuration1.AppSettings.Settings["SMTP Port"].Value;
                textBox8.Text = configuration1.AppSettings.Settings["From Address"].Value;
                textBox10.Text = BinaryToString(re_order(configuration1.AppSettings.Settings["From Password"].Value));
                textBox9.Text = configuration1.AppSettings.Settings["To Address"].Value;
                textBox5.Text = configuration1.AppSettings.Settings["Log File"].Value;
                comboBox2.SelectedItem = configuration1.AppSettings.Settings["Number of Retries"].Value;
                checkBox1.Checked = System.Convert.ToBoolean(configuration1.AppSettings.Settings["SSRS_Configure"].Value);
                checkBox2.Checked = System.Convert.ToBoolean(configuration1.AppSettings.Settings["SSIS_Configure"].Value);
                checkBox3.Checked = System.Convert.ToBoolean(configuration1.AppSettings.Settings["SSAS_Configure"].Value);
                checkBox4.Checked = System.Convert.ToBoolean(configuration1.AppSettings.Settings["SQL_Configure"].Value);
                string s1 = configuration1.AppSettings.Settings["SSRS_SOAP_RB"].Value;
        
        
                if (configuration1.AppSettings.Settings["Windows Auth"].Value == "1")
                {
                    panel3.Enabled = false;
                    radioButton2.Checked = false;
                }
                else
                {
                    panel3.Enabled = true;
                    radioButton2.Checked = true;
                }


                //If you select to check for SSRS....................

                if (checkBox1.Checked)
                {
                    try
                    {
                        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(System.Configuration.ConfigurationSettings.AppSettings["Report Server URL"].ToString());
                        webRequest.Credentials = CredentialCache.DefaultCredentials;
                        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                        sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "Report Server URL - Working fine");
                        try
                        {
                            string wsdl = textBox2.Text + ((s1 == "0") ? "/ReportService2010.asmx?wsdl" : "/ReportService2005.asmx?wsdl");
                            Properties.Settings.Default.BIMonitoring_localhost_ReportingService2010 = wsdl;
                            Properties.Settings.Default.Save();
                            ReportingService2010 rs1 = new ReportingService2010();
                            rs1.Credentials = System.Net.CredentialCache.DefaultCredentials;
                            CatalogItem[] items = null;
                            items = rs1.ListChildren("/", true);
                        }
                        catch (SoapException ex1)
                        {
                            try
                            {
                                int rs_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["RS_Error_Count"].ToString());
                                if (++rs_error_count == retry_count)
                                {
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "Report Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    send_email("Date&Time: " + System.DateTime.Now + "\n" + "Report Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                    configuration.AppSettings.Settings["RS_Error_Count"].Value = "0";
                                    configuration.Save(ConfigurationSaveMode.Modified);
                                    ConfigurationManager.RefreshSection("appSettings");
                                }
                                else
                                {
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "The Reporting Services site is up but reports are not accessible." + "\n" + ex1.ToString());
                                }
                            }

                            catch (Exception ex3)
                            {
                                //
                            }
                            
                        }
                    }

                    catch (Exception ex1)
                    {
                        try
                        {
                            int rs_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["RS_Error_Count"].ToString());
                            if (++rs_error_count == retry_count)
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "Report Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                send_email("Date&Time: " + System.DateTime.Now + "\n" + "Report Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                configuration.AppSettings.Settings["RS_Error_Count"].Value = "0";
                                configuration.Save(ConfigurationSaveMode.Modified);
                                ConfigurationManager.RefreshSection("appSettings");
                            }
                            else
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "Report Server URL - Error Details: " + "\n" + ex1.ToString());
                            }
                        }

                        catch (Exception ex3)
                        {
                            //
                        }

                    }

                    try
                    {
                        HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create(System.Configuration.ConfigurationSettings.AppSettings["Report Manager URL"].ToString());
                        webRequest1.Credentials = CredentialCache.DefaultCredentials;
                        HttpWebResponse response1 = (HttpWebResponse)webRequest1.GetResponse();
                        sw1.WriteLine("Date&Time: " + System.DateTime.Now + "  " + "Report Manager URL - Working fine");
                    }

                    catch (Exception ex2)
                    {
                        try
                        {
                            int rm_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["RM_Error_Count"].ToString());
                            if (++rm_error_count == retry_count)
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "Report Manager Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex2.ToString());
                                send_email("Date&Time: " + System.DateTime.Now + "\n" + "Report Manager Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex2.ToString());
                                System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                configuration.AppSettings.Settings["RM_Error_Count"].Value = "0";
                                configuration.Save(ConfigurationSaveMode.Modified);
                                ConfigurationManager.RefreshSection("appSettings");
                            }
                            else
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "Report Manager URL - Error Details: " + "\n" + ex2.ToString());
                            }
                        }

                        catch (Exception ex4)
                        {
                            //
                        }
                    }
                }

                else
                {
                    label2.Enabled = false;
                    textBox2.Enabled = false;
                    label3.Enabled = false;
                    textBox3.Enabled = false;
                    button2.Enabled = false;
                    button3.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                }


                //If you select to test for SSIS.......................

                if (checkBox2.Checked)
                {
                    try
                    {
                        string sqlFolder;
                        string sqlServer;

                        Microsoft.SqlServer.Dts.Runtime.Application ssisApplication;
                        PackageInfos sqlPackages;

                        sqlServer = System.Configuration.ConfigurationSettings.AppSettings["Integration Services Server"].ToString();

                        ssisApplication = new Microsoft.SqlServer.Dts.Runtime.Application();

                        // Get packages stored in MSDB.
                        sqlFolder = "MSDB";
                        sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer);
                        sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "SQL Server Integration Services (SSIS) - Working fine.");
                    }
                    catch (Exception ex1)
                    {
                        try
                        {
                            int ssis_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SSIS_Error_Count"].ToString());
                            if (++ssis_error_count == retry_count)
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "SQL Server Integration Services (SSIS) Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                send_email("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Integration Services (SSIS) Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                configuration.AppSettings.Settings["SSIS_Error_Count"].Value = "0";
                                configuration.Save(ConfigurationSaveMode.Modified);
                                ConfigurationManager.RefreshSection("appSettings");
                            }

                            else
                            {
                                sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Integration Services (SSIS) - Error Details" + "\n" + ex1.ToString());

                            }
                        }

                        catch (Exception ex)
                        {
                            //
                        }

                    }
                }

                else
                {
                    label1.Enabled = false;
                    textBox4.Enabled = false;
                    button7.Enabled = false;
                    button8.Enabled = false;
                    button9.Enabled = false;
                }



                //If you select to test for SSAS.......................


                if (checkBox3.Checked)
                {
                    using (Server myserver = new Server())
                    {
                        try
                        {
                            myserver.Connect(System.Configuration.ConfigurationSettings.AppSettings["Analysis Services Server"].ToString());
                            myserver.Disconnect();
                            sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "SQL Server Analyis Services (SSAS) - Working fine.");
                        }
                        catch (Exception ex1)
                        {
                            try
                            {
                                int ssas_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SSAS_Error_Count"].ToString());
                                if (++ssas_error_count == retry_count)
                                {
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "SQL Server Analyis Services (SSAS) Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    send_email("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Analyis Services (SSAS) Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                    configuration.AppSettings.Settings["SSAS_Error_Count"].Value = "0";
                                    configuration.Save(ConfigurationSaveMode.Modified);
                                    ConfigurationManager.RefreshSection("appSettings");
                                }
                                else
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Analyis Services (SSAS) - Error Details: " + "\n" + ex1.ToString());
                            }

                            catch (Exception ex)
                            {
                                //
                            }
                        }

                    }
                }


                else
                {
                    label5.Enabled = false;
                    textBox6.Enabled = false;
                    button10.Enabled = false;
                    button11.Enabled = false;
                    button12.Enabled = false;
                }


                //If you select to test for SQL Server ..........................


                if (checkBox4.Checked)
                {
                    using (SqlConnection conn = new SqlConnection())
                    {
                        conn.ConnectionString = "Persist Security Info=False;" + ((System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Windows Auth"].ToString()) == 1) ? "Integrated Security = true; Server= " + System.Configuration.ConfigurationSettings.AppSettings["SQL Server"].ToString() : "Server= " + System.Configuration.ConfigurationSettings.AppSettings["SQL Server"].ToString() + ";User =  " + System.Configuration.ConfigurationSettings.AppSettings["SQL User"].ToString() + ";Password =  " + BinaryToString(re_order(System.Configuration.ConfigurationSettings.AppSettings["SQL Password"].ToString())));
                        try
                        {
                            conn.Open();
                            sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "SQL Server - Working fine.");
                        }

                        catch (SqlException ex1)
                        {
                            try
                            {
                                int sql_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SQL_Error_Count"].ToString());
                                if (++sql_error_count == retry_count)
                                {
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "SQL Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    send_email("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex1.ToString());
                                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                    configuration.AppSettings.Settings["SQL_Error_Count"].Value = "0";
                                    configuration.Save(ConfigurationSaveMode.Modified);
                                    ConfigurationManager.RefreshSection("appSettings");
                                }
                                else
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server - Error Details" + "\n" + ex1.ToString());
                            }
                            catch (Exception ex)
                            {
                                //
                            }

                        }

                        catch (Exception ex2)
                        {
                            try
                            {
                                int sql_error_count = System.Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SQL_Error_Count"].ToString());
                                if (++sql_error_count == retry_count)
                                {
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + " " + "SQL Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex2.ToString());
                                    send_email("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server Not Functioning Appropriately, it has reached the retry count. Error Details: " + "\n" + ex2.ToString());
                                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                    configuration.AppSettings.Settings["SQL_Error_Count"].Value = "0";
                                    configuration.Save(ConfigurationSaveMode.Modified);
                                    ConfigurationManager.RefreshSection("appSettings");
                                }
                                else
                                    sw1.WriteLine("Date&Time: " + System.DateTime.Now + "\n" + "SQL Server - Error Details" + "\n" + ex2.ToString());
                            }
                            catch (Exception ex)
                            {
                                //
                            }
                        }
                    }
                }

                else
                {
                    label12.Enabled = false;
                    textBox11.Enabled = false;
                    panel2.Enabled = false;
                    panel3.Enabled = false;
                    button15.Enabled = false;
                    button16.Enabled = false;
                    button17.Enabled = false;
                }
                sw1.WriteLine("============ Testing Cycle Over ============");
                sw1.WriteLine();
                sw1.Close();
                sw1.Dispose();

            }

            catch (Exception ex)
            {
                MessageBox.Show("Issues with the Log File creation, please make sure that file '" + System.Configuration.ConfigurationSettings.AppSettings["Log File"].ToString() + "' exists. If it doesn't please either create one or change the path in the configuration file.");
            }

        }


        
        // Send Email during failure with particular subject 

        public void send_email(string body)
        {
            try
            {
                System.Configuration.Configuration configuration1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(configuration1.AppSettings.Settings["SMTP Server"].Value);
                SmtpServer.Credentials = new System.Net.NetworkCredential(configuration1.AppSettings.Settings["From Address"].Value, BinaryToString(re_order((configuration1.AppSettings.Settings["From Password"].Value))));
                mail.From = new MailAddress(configuration1.AppSettings.Settings["From Address"].Value);
                mail.To.Add(configuration1.AppSettings.Settings["To Address"].Value);
                mail.Subject = "BI Monitoring Tool - Exception";
                mail.Body = body;
                SmtpServer.Port = 587;
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
            catch (Exception ex1)
            {
                //Capture exceptions while sending emails.

            }
        }
        
         


        //Main SAVE button
         private void button1_Click(object sender, EventArgs e)
         {
             System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             configuration.AppSettings.Settings["Log File"].Value = textBox5.Text;
             configuration.AppSettings.Settings["Number of Retries"].Value = comboBox2.SelectedItem.ToString();
             configuration.Save(ConfigurationSaveMode.Modified);
             ConfigurationManager.RefreshSection("appSettings");
             MessageBox.Show("Changes saved", "Information", MessageBoxButtons.OK);
         }


         //////////////////////////////////////////////////////////////////////////////////
         //Convert Password.....


         public static string StringToBinary(string data)
         {
             StringBuilder sb = new StringBuilder();

             foreach (char c in data.ToCharArray())
             {
                 sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
             }
             return sb.ToString();
         }

         public static string BinaryToString(string data)
         {
             List<Byte> byteList = new List<Byte>();

             for (int i = 0; i < data.Length; i += 8)
             {
                 byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
             }

             return Encoding.ASCII.GetString(byteList.ToArray());
         }

         public static string re_order(string data)
         {
             int j = data.Length / 8;
             string s2 = null;

             for (int i = 0; i < (data.Length / 8); i++)
             {
                 StringBuilder s3 = new StringBuilder(data.Substring(i * 8, 8));
                 for (int z = 0; z < 8; z++)
                 {
                     char c = s3[z];
                     s3[z] = s3[7 - z];
                     s3[7 - z] = c;
                 }
                 s2 = s3 + s2;
             }

             return s2 + data.Substring(j, data.Length % 8);
         }


         /////Convert Password Ends.............
         //////////////////////////////////////////////////////////////////////////////////



         //////////////////////////////////////////////////////////////////////////////////
         //SSRS Section begins...............


         //Test Report Server URL
         private void button2_Click(object sender, EventArgs e)
         {

             try
             {
                 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(textBox2.Text);
                 webRequest.Credentials = CredentialCache.DefaultCredentials;
                 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                 MessageBox.Show("Test Connection successful", "Information", MessageBoxButtons.OK);
             }
             catch (Exception ex1)
             {
                 MessageBox.Show("Exception: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);
             }
         }

        //Test Report Manager URL
         private void button3_Click(object sender, EventArgs e)
         {
             try
             {
                 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(textBox3.Text);
                 webRequest.Credentials = CredentialCache.DefaultCredentials;
                 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                 MessageBox.Show("Test Connection successful", "Information", MessageBoxButtons.OK);
             }
             catch (Exception ex1)
             {
                 MessageBox.Show("Exception: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy messgae ", MessageBoxButtons.OK);
             }
         }

        //Clear Button
         private void button5_Click(object sender, EventArgs e)
         {
             System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             textBox2.Text = configuration.AppSettings.Settings["Report Server URL"].Value;
             textBox3.Text = configuration.AppSettings.Settings["Report Manager URL"].Value; 
         }

        //Apply Changes
         private void button4_Click(object sender, EventArgs e)
         {
             System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             configuration.AppSettings.Settings["Report Server URL"].Value = textBox2.Text;
             if(radioButton6.Checked) configuration.AppSettings.Settings["SSRS_SOAP_RB"].Value = "1";
             else configuration.AppSettings.Settings["SSRS_SOAP_RB"].Value = "0";
             configuration.AppSettings.Settings["Report Manager URL"].Value = textBox3.Text;
             configuration.AppSettings.Settings["SSRS_Configure"].Value = checkBox1.Checked.ToString();
             configuration.Save(ConfigurationSaveMode.Modified);
             ConfigurationManager.RefreshSection("appSettings");
             MessageBox.Show("Changes saved", "Information", MessageBoxButtons.OK);
         }

        //SSRS Section Ends##################
        //////////////////////////////////////////////////////////////////////////////////




        ///////////////////////////////////////////////////////////////////////////////////
        //SQL Server begins.......

         public string getConnString()
         {
             return "Persist Security Info=False;" + ((radioButton1.Checked) ? ("Integrated Security=true; Server =" + textBox11.Text) : ("Server =" + textBox11.Text + "; User =" + textBox13.Text + "; Password =" + textBox12.Text));
         }

        //Test Connection
         private void button15_Click(object sender, EventArgs e)
         {
             using (SqlConnection conn = new SqlConnection())
             {
                 conn.ConnectionString = getConnString();
                 try
                 {
                     conn.Open();
                     MessageBox.Show("Test Connection successful", "Information", MessageBoxButtons.OK);
                 }

                 catch (SqlException ex1)
                 {
                     MessageBox.Show("SQL Exception: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);
                 }

                 catch (Exception ex2)
                 {
                     MessageBox.Show("Exception: " + ex2.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);
                 }
             }
         }

        //Clear Button
         private void button16_Click(object sender, EventArgs e)
         {
             System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             textBox11.Text = configuration.AppSettings.Settings["SQL Server"].Value;
             textBox12.Text = BinaryToString(re_order(configuration.AppSettings.Settings["SQL Password"].Value));
             textBox13.Text = configuration.AppSettings.Settings["SQL User"].Value;
             if (configuration.AppSettings.Settings["Windows Auth"].Value == "0") radioButton2.Checked = true;
             else  radioButton1.Checked = true;  

         }
        
        //Save Button
         private void button17_Click(object sender, EventArgs e)
         {
             System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             configuration.AppSettings.Settings["SQL Server"].Value = textBox11.Text;
             configuration.AppSettings.Settings["SQL User"].Value = textBox13.Text;
             configuration.AppSettings.Settings["SQL_Configure"].Value = checkBox4.Checked.ToString();
             if (radioButton2.Checked)
             {
                 configuration.AppSettings.Settings["Windows Auth"].Value = "0";
                 configuration.AppSettings.Settings["SQL Password"].Value = re_order(StringToBinary(textBox12.Text));
             }
             else
             {
                 configuration.AppSettings.Settings["Windows Auth"].Value = "1"; configuration.AppSettings.Settings["SQL Password"].Value = "";
             }
             configuration.Save(ConfigurationSaveMode.Modified);
             ConfigurationManager.RefreshSection("appSettings");
             MessageBox.Show("Changes saved", "Information", MessageBoxButtons.OK);
         }

         
        //SQL Server Ends###############
        ///////////////////////////////////////////////////////////////////////////////////





        ///////////////////////////////////////////////////////////////////////////////////
        //SSIS begins..............

        //Test Connection             
       private void button7_Click(object sender, EventArgs e)
         {

             try
             {
                 string sqlFolder;
                 string sqlServer;

                 Microsoft.SqlServer.Dts.Runtime.Application ssisApplication;
                 PackageInfos sqlPackages;

                 sqlServer = textBox4.Text;

                 ssisApplication = new Microsoft.SqlServer.Dts.Runtime.Application();

                 // Get packages stored in MSDB.
                 sqlFolder = "MSDB";
                 sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer);
                 MessageBox.Show("Test Connection successful", "Information", MessageBoxButtons.OK);
             }
             catch (Exception ex1)
             {
                 MessageBox.Show("Exception: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);

             }
         }

        //Clear button
       private void button9_Click(object sender, EventArgs e)
       {
           System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           textBox4.Text = configuration.AppSettings.Settings["Integration Services Server"].Value;
       }

        //Save button
       private void button8_Click(object sender, EventArgs e)
       {
           System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           configuration.AppSettings.Settings["Integration Services Server"].Value = textBox4.Text;
           configuration.AppSettings.Settings["SSIS_Configure"].Value = checkBox2.Checked.ToString();
           configuration.Save(ConfigurationSaveMode.Modified);
           ConfigurationManager.RefreshSection("appSettings");
           MessageBox.Show("Changes saved", "Information", MessageBoxButtons.OK);   
       }

       //SSIS Ends############
       ///////////////////////////////////////////////////////////////////////////////////




        ///////////////////////////////////////////////////////////////////////////////////
        //SSAS begins...............

       

        private void button12_Click(object sender, EventArgs e)
        {
             using (Server myserver = new Server())
            {
                try
                {
                    myserver.Connect(textBox6.Text);
                    MessageBox.Show("Test Connection successful", "Information", MessageBoxButtons.OK);
                    myserver.Disconnect();
                }
                catch (Exception ex1)
                {
                    MessageBox.Show("Exception: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);
                }

            }
        }

        //Save Button
        private void button10_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["Analysis Services Server"].Value = textBox6.Text;
            configuration.AppSettings.Settings["SSAS_Configure"].Value = checkBox3.Checked.ToString();
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            MessageBox.Show("Changes saved", "Information", MessageBoxButtons.OK);

        }

        //Clear button
        private void button11_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            textBox6.Text = configuration.AppSettings.Settings["Analysis Services Server"].Value;
        }


        //SSAS Ends###########
        ///////////////////////////////////////////////////////////////////////////////////


        ///////////////////////////////////////////////////////////////////////////////////
        //Email Settings................

       
        //Send Test Email
        private void button18_Click(object sender, EventArgs e)
        {


            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(comboBox1.SelectedItem.ToString());
                SmtpServer.Credentials = new System.Net.NetworkCredential(textBox8.Text, textBox10.Text);
                mail.From = new MailAddress(textBox8.Text);
                mail.To.Add(textBox9.Text);
                mail.Subject = "Test Mail from BI Configuration Manager";
                mail.Body = "Congratulations. You got the test email to go through successfully!";
                SmtpServer.Port = System.Convert.ToInt32(textBox7.Text);
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
                MessageBox.Show("Email Send sucessfully. Please confirm that you have received it and then proceed. It might take some time.", "Information", MessageBoxButtons.OK);
            }
            catch (Exception ex1)
            {
                MessageBox.Show("Something went wrong: " + ex1.ToString(), "Exception - Press 'Ctrl-C' to copy message ", MessageBoxButtons.OK);
            }

        }

        //Open Default ports link
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list.html");
        }


        //Save Settings
        private void button13_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["SMTP Server"].Value = comboBox1.SelectedItem.ToString();
            configuration.AppSettings.Settings["SMTP Port"].Value = textBox7.Text;
            configuration.AppSettings.Settings["From Address"].Value = textBox8.Text;
            configuration.AppSettings.Settings["From Password"].Value = re_order(StringToBinary(textBox10.Text));
            configuration.AppSettings.Settings["To Address"].Value = textBox9.Text;
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            MessageBox.Show("Changes saved");
        }

        //Clear settings
        private void button14_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            comboBox1.SelectedItem = configuration.AppSettings.Settings["SMTP Server"].Value;
            textBox7.Text = configuration.AppSettings.Settings["SMTP Port"].Value;
            textBox8.Text = configuration.AppSettings.Settings["From Address"].Value;
            textBox10.Text = BinaryToString(re_order(configuration.AppSettings.Settings["From Password"].Value));
            textBox9.Text = configuration.AppSettings.Settings["To Address"].Value;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            panel3.Enabled = true;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            panel3.Enabled = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
            {
                label2.Enabled = true;
                textBox2.Enabled = true;
                label3.Enabled = true;
                textBox3.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                textBox1.Enabled = true;
                panel4.Enabled = true;
            }
            else
            {
                label2.Enabled = false;
                textBox2.Enabled = false;
                label3.Enabled = false;
                textBox3.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                button5.Enabled = false;
                textBox1.Enabled = false;
                panel4.Enabled = false;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
            {
                label1.Enabled = true;
                textBox4.Enabled = true;
                button7.Enabled = true;
                button8.Enabled = true;
                button9.Enabled = true;
            }

            else
            {
                label1.Enabled = false;
                textBox4.Enabled = false;
                button7.Enabled = false;
                button8.Enabled = false;
                button9.Enabled = false;
            }

        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
            {
                label5.Enabled = true;
                textBox6.Enabled = true;
                button10.Enabled = true;
                button11.Enabled = true;
                button12.Enabled = true;
            }

            else
            {
                label5.Enabled = false;
                textBox6.Enabled = false;
                button10.Enabled = false;
                button11.Enabled = false;
                button12.Enabled = false;
            }
            
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
            {
                label12.Enabled = true;
                textBox11.Enabled = true;
                panel2.Enabled = true;
                panel3.Enabled = true;
                button15.Enabled = true;
                button16.Enabled = true;
                button17.Enabled = true;
                if (System.Configuration.ConfigurationSettings.AppSettings["From Password"].ToString() == "")
                    panel3.Enabled = false;

            }

            else
            {
                label12.Enabled = false;
                textBox11.Enabled = false;
                panel2.Enabled = false;
                panel3.Enabled = false;
                button15.Enabled = false;
                button16.Enabled = false;
                button17.Enabled = false;
            }
        }



        //Email Settings #############
        ////////////////////////////////////////////////////////////////////////////////////////



        //Browse button
        private void button6_Click(object sender, EventArgs e)
        {
            string file;
            var openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                file = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
            }
            else
                file = textBox5.Text;
            textBox5.Text = file;
            if (file.Contains(".txt") == false)
            {
                file += "Output.txt";
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!File.Exists(System.Configuration.ConfigurationSettings.AppSettings["Log File"].ToString()))
            {
                DialogResult dr= MessageBox.Show("Log File mentioned doesn't exist, please either create one or change the location to a valid one and apply the changes. Do you still want to continue with the EXIT of the program.", "Information : EXIT",MessageBoxButtons.YesNoCancel);
                if (dr == DialogResult.No || dr == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }


            }
        }


     }
}



//.................................    Program Ends  ............................................... //